package demo;

/**
 *   两数相加
 *
 */
class Solution39 {
	public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		int carry = 0;
		ListNode result = new ListNode(0);
		ListNode dummy = result;
		while (l1 != null || l2 != null) {
			int x = l1 == null ? 0 : l1.val;
			int y = l2 == null ? 0 : l2.val;
			int sum = (x + y + carry) % 10;
			carry = sum/10;
			ListNode cur = new ListNode(sum);
			result.next = cur;
			result = cur;
			if (l1 != null) {
				l1 = l1.next;
			}
			if (l2 != null) {
				l2 = l2.next;
			}
		}
		if (carry > 0) {
			result.next = new ListNode(carry);
		}
		return dummy.next;
	}

	public static void main(String[] args) {
		ListNode first0 = new ListNode(2);
		ListNode first1 = new ListNode(4);
		ListNode first2 = new ListNode(3);
		first0.next = first1;
		first1.next = first2;

		ListNode second0 = new ListNode(5);
		ListNode second1 = new ListNode(6);
		ListNode second2 = new ListNode(4);
		second0.next = second1;
		second1.next = second2;

		System.out.println(new Solution39().addTwoNumbers(first0, second0).val);
	}
}

